/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core.tabs;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Action;
import org.netbeans.modules.tfsnb.core.ConnectionSettings;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.windows.TopComponent;
import org.reflections.Reflections;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class TabManager implements TabPanelCallback {
    
    private Map<String, TabPanel> views;
    private final TopComponent topComponent;
        
    private static final Logger LOG = Logger.getLogger(TabManager.class.getName());  
    private String topComponentId;
    private Reflections reflections;
    private final ConnectionSettings connectionSettings;
    

    public TabManager(final TopComponent topComponent, final ConnectionSettings connectionSettings) throws Exception {
        this.topComponent = topComponent;
        this.connectionSettings = connectionSettings;
        Annotation[] topComponentAnnotations = topComponent.getClass().getAnnotations();
        for(Annotation annotation: topComponentAnnotations) {
            if(annotation.annotationType().equals(TopComponent.Description.class)) {
                this.topComponentId = ((TopComponent.Description) annotation).preferredID();
            }
        }
        if(views == null) lookupMultiviews();
        if(topComponentId == null) throw new Exception("TopComponent should have a preferredId. Look at TopComponent.Description annotation.");
    }
    
    private void lookupMultiviews() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        if(views == null ) views = new HashMap<>();
        FileObject fileObject = FileUtil.getConfigRoot();
        FileObject explorer = fileObject.getFileObject("TFS/Explorer/MultiView");
        FileObject[] multiViews = explorer.getChildren();        
                
        for(FileObject multiView: multiViews) {
            String className = (String) multiView.getAttribute("instance");
            String displayName = (String) multiView.getAttribute("displayName");
            String iconBase = (String) multiView.getAttribute("iconBase");
            String id = (String) multiView.getAttribute("id");
            String topComponentPreferredId = (String) multiView.getAttribute("topComponentPreferredId");
            int position = (int) multiView.getAttribute("position");
            
            TabPanelDescription multiViewDescription = new TabPanelDescription(displayName, iconBase, id, topComponentPreferredId, position);      
            InstanceCookie cookie = multiView.getLookup().lookup(InstanceCookie.class);
            TabPanel multiViewPanel = (TabPanel) cookie.instanceCreate();
            
            multiViewPanel.setId(topComponentId + "_" + multiViewDescription.getId());
            multiViewPanel.setMultiViewPanelDescription(multiViewDescription);
            multiViewPanel.setLookup(topComponent.getLookup());
            multiViewPanel.setMultiViewCallback(this);  
            multiViewPanel.setConnectionSettings(connectionSettings);
            multiViewPanel.postConstruct();
            views.put(multiViewPanel.getId(), multiViewPanel);
        }
    }
    
    public TabPanel getMultiViewPanel(final String panelId) {
        if(views == null) {
            try {
                lookupMultiviews();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException ex) {
                LOG.log(Level.SEVERE,  ex.getMessage());
            }
        }
        
        return views.get(panelId);
    }
    
    /**
     * 
     * @param reload a {boolean} value indicating whether to force reload.
     * @return 
     */
    public Map<String, TabPanel> getViews(final boolean reload) {
        if(views == null || views.isEmpty() || reload) {
            try {
                lookupMultiviews();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException ex) {
                LOG.log(Level.SEVERE,  ex.getMessage());
            }
        }
        return views;
    }
        
    /**
     *
     * @param multiView     
     */
    public static void createMultiViewPanel(final FileObject multiView) {
        String displayName = (String) multiView.getAttribute("displayName");
        String iconBase = (String) multiView.getAttribute("iconBase");
        String id = (String) multiView.getAttribute("id");
        String topComponentPreferredId = (String) multiView.getAttribute("topComponentPreferredId");            
        int position = Integer.parseInt((String) multiView.getAttribute("position"));

        TabPanelDescription multiViewDescription = new TabPanelDescription(displayName, iconBase, id, topComponentPreferredId, position);          
    }
    
    // start: TabPanelCallback
    @Override
    public Action[] createDefaultActions() {
        return new Action[0];
    }

    @Override
    public void updateTitle(String title) {
        topComponent.setDisplayName(title);
    }

    @Override
    public boolean isSelectedElement() {
        return true;
    }

    @Override
    public TopComponent getTopComponent() {
        return topComponent;
    }   

    @Override
    public void requestActive() {
        
    }

    @Override
    public void requestVisible() {
        
    }
    // end: TabPanelCallback
}
